# -*- coding: utf-8 -*-

from django.utils.functional import curry
from django.contrib.markup.templatetags.markup import textile

from djmarkitup import settings


DJMIU_MARKUP_CHOICES = [
    (u'textile', u'Textile'),
]

DJMIU_MARKUP_RENDERERS = {
    'textile': curry(textile),
}


if settings.DJMIU_PYGMENTS_STYLE:
    try:
        import pygments
    except ImportError:
        pygments = None
        print ('No Pygments installation found, but usage is enabled in '
               'settings.py.')


try:
    from docutils.core import publish_parts
    if settings.DJMIU_PYGMENTS_STYLE and pygments is not None:
        from djmarkitup import rst_directives

    def render_rest(text, **docutils_options):
        parts = publish_parts(source=text, writer_name='html4css1',
            settings_overrides=docutils_options)
        return parts['html_body']
    DJMIU_MARKUP_CHOICES.append((u'rest', u'ReStructuredText'))
    DJMIU_MARKUP_RENDERERS['rest'] = curry(render_rest)
except ImportError:
    pass


try:
    from markdown import Markdown
    if settings.DJMIU_PYGMENTS_STYLE and pygments is not None:
        from djmarkitup.markdown_processors import CodeBlockPreprocessor
        use_pygments = True
    else:
        use_pygments = False

    def render_markdown(text, **markdown_options):
        md = Markdown(extensions=['extra'], **markdown_options)
        if use_pygments:
            md.textPreprocessors.insert(0, CodeBlockPreprocessor)
        html = md.convert(text)
        return html
    DJMIU_MARKUP_CHOICES.append((u'markdown', u'Markdown'))
    DJMIU_MARKUP_RENDERERS['markdown'] = curry(render_markdown,
        safe_mode='escape', output_format='html5')
except ImportError:
    pass
